
package com.kugou.game.sdk.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.kugou.game.sdk.core.PayManager;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.PayConstant.ChargeIndexMode;
import com.kugou.game.sdk.entity.PayConstant.ChargeType;
import com.kugou.game.sdk.interfaces.OnPayCheckListener;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.ToastUtil;

/**
 * 描述:充值查询
 *
 * @author wcj
 * @since 2015年11月16日 上午9:41:14
 */
public class CheckRechargeResultFragment extends BaseRechargeFragment {

    public static final String ORDER_ID = "order_id";

    public static final String ORDER_VALUE = "order_value";

    public static final int REQUEST_CARD_RESULT_CODE = 10001;

    public static final int RESPONSE_CARD_SUCCESS_CODE = 10002;

    public static final int RESPONSE_CARD_FAILED_CODE = 10003;

    private final int MSG_BACK_REQUEST_PHONE_CARD_RESULT = 8;

    private final int MSG_REQUEST_PHONE_CARD_RESULT_START = 9;

    private final int MSG_REQUEST_PHONE_CARD_RESULT_SUCCESS = 10;

    private final int MSG_REQUEST_PHONE_CARD_RESULT_WAITING = 11;

    private final int MSG_REQUEST_PHONE_CARD_RESULT_FAILED = 12;

    private final int MSG_COUNT_START = 13;

    private final int INTERVAL_TIME = 10000;

    private Button mCheckResultButton, mQuitToGameButton;

    private ImageView mCheckStateImageView;

    private String mOrderId;

    private int mOrderValue;

    private int mRechargeMode;

    private int mCountDownMinute = 180;

    public static CheckRechargeResultFragment getFragment(String order, int money, int mode) {
        CheckRechargeResultFragment fragment = new CheckRechargeResultFragment();
        fragment.mOrderId = order;
        fragment.mOrderValue = money;
        fragment.mRechargeMode = mode;
        return fragment;
    }

    private CheckRechargeResultFragment() {
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initViews();

        requestMobileCardResult();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(Rx.layout.kg_fragment_check_recharge_result, null);
    }

    private void initViews() {
        mCheckResultButton = (Button) findViewById(Rx.id.kg_btn_check_result);
        mCheckResultButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                requestMobileCardResult();
            }
        });

        mQuitToGameButton = (Button) findViewById(Rx.id.kg_btn_quit_kugou);
        if (!mIsRechargeYoubi) {
            mQuitToGameButton.setText("退出游戏充值");
        }

        mQuitToGameButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                enterGame();
            }
        });

        mCheckStateImageView = (ImageView) findViewById(Rx.id.kg_iv_check_state);
    }

    private void enterGame() {
        // 回到游戏
        Intent intent = new Intent(SDKActions.ACTION_BACK_TO_GAME);
        getActivity().sendBroadcast(intent);
    }

    public void requestMobileCardResult() {
        // 检测电话卡是否充值成功
        sendEmptyUiMessageDelayed(MSG_REQUEST_PHONE_CARD_RESULT_START, 100);
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        switch (msg.what) {
            case MSG_BACK_REQUEST_PHONE_CARD_RESULT:
                checkPay();
                break;

            default:
                break;
        }
    }

    @Override
    public void handleUiMessage(Message msg) {
        if (getActivity() == null || getActivity().isFinishing() || isDetached() || !isAdded()) {
            return;
        }

        switch (msg.what) {
            case MSG_REQUEST_PHONE_CARD_RESULT_START:
                // 开始倒数
                sendEmptyUiMessage(MSG_COUNT_START);
                // 十秒后开始第一次查询
                sendEmptyBackgroundMessageDelayed(MSG_BACK_REQUEST_PHONE_CARD_RESULT, INTERVAL_TIME);
                // 设置按钮状态
                mQuitToGameButton.setEnabled(false);
                mQuitToGameButton.setBackgroundResource(Rx.drawable.kg_shape_gray_btn_unable);
                mCheckResultButton.setEnabled(false);

                mCheckStateImageView.setImageResource(Rx.drawable.kg_img_checking);
                // sendEmptyUiMessage(MSG_REQUEST_PHONE_CARD_RESULT_SUCCESS);
                break;
            case MSG_REQUEST_PHONE_CARD_RESULT_SUCCESS:
                onRechargeResultChange(false);
                removeUiMessage(MSG_COUNT_START);

                mCheckStateImageView.setImageResource(Rx.drawable.kg_img_checked);

                // 发送统计--支付成功
                sendRechargeSuccessEvent(mOrderId, mRechargeMode, mOrderValue);

                if (getOnEventListener() != null) {
                    int mode = ChargeIndexMode.MODE_MOBILE_CARD;
                    if (mRechargeMode == ChargeType.TYPE_GAME_CARD) {
                        mode = ChargeIndexMode.MODE_GAME_CARD;
                    }
                    getOnEventListener().onRechargeSuccess(mode, mOrderValue);
                }

                break;

            case MSG_REQUEST_PHONE_CARD_RESULT_WAITING:
                mCheckStateImageView.setImageResource(Rx.drawable.kg_img_checked);

                // 已经大于60秒,让退出按钮可点击
                if (mCountDownMinute < 120) {
                    ToastUtil.showMsg("网络较慢，可先退出查询页面进行其他操作。");
                    mQuitToGameButton.setEnabled(true);
                    mQuitToGameButton.setBackgroundResource(Rx.drawable.kg_selector_btn_gray);
                }

                removeBackgroundMessage(MSG_BACK_REQUEST_PHONE_CARD_RESULT);
                sendEmptyBackgroundMessageDelayed(MSG_BACK_REQUEST_PHONE_CARD_RESULT, INTERVAL_TIME);

                break;

            case MSG_REQUEST_PHONE_CARD_RESULT_FAILED:
                onRechargeResultChange(false);
                removeUiMessage(MSG_COUNT_START);
                mCheckResultButton.setText("查看本次游戏充值结果");
                mQuitToGameButton.setEnabled(true);
                mQuitToGameButton.setBackgroundResource(Rx.drawable.kg_selector_btn_gray);
                mCheckResultButton.setEnabled(true);

                ToastUtil.showMsg(msg.obj.toString());

                mCheckStateImageView.setImageResource(Rx.drawable.kg_img_checked);

                break;
            case MSG_COUNT_START:
                onRechargeResultChange(true);
                mCheckResultButton.setText("(" + mCountDownMinute + ")正在查询充值结果，请稍后…");
                if (mCountDownMinute > 0) {
                    mCountDownMinute--;
                } else {
                    mCountDownMinute = 180;
                    // 恢复按钮
                    showToast("由于网络延时，未能及时查询到结果");
                    // 取消请求循环
                    removeBackgroundMessage(MSG_BACK_REQUEST_PHONE_CARD_RESULT);
                    mCheckResultButton.setText("重新查询");
                    mQuitToGameButton.setEnabled(true);
                    mCheckResultButton.setEnabled(true);
                    return;
                }
                sendEmptyUiMessageDelayed(MSG_COUNT_START, 1000);
                break;

            default:
                break;
        }
    }

    /**
     * 修改充值查询状态
     * 
     * @param isChecking
     */
    private void onRechargeResultChange(boolean isChecking) {
        if (getOnEventListener() != null) {
            getOnEventListener().onRechargeResultChange(isChecking);
        }
    }

    /**
     * 发送请求验证充值结果
     */
    private synchronized void checkPay() {
        PayManager.checkPay(UserManager.getInstance().getCurrentUserInternal().getAccountName(),
                mOrderId, mRechargeMode, onPayCheckListener);
    }

    OnPayCheckListener onPayCheckListener = new OnPayCheckListener() {

        @Override
        public void onSuccess() {
            Message msg = new Message();
            msg.what = MSG_REQUEST_PHONE_CARD_RESULT_SUCCESS;
            sendUiMessage(msg);
        }

        @Override
        public void onWaiting() {
            Message msg = new Message();
            msg.what = MSG_REQUEST_PHONE_CARD_RESULT_WAITING;
            sendUiMessage(msg);
        }

        @Override
        public void onFailed(String errorMsg) {
            Message msg = new Message();
            msg.what = MSG_REQUEST_PHONE_CARD_RESULT_FAILED;
            msg.obj = errorMsg;
            sendUiMessage(msg);
        }
    };
}
